package com.yxx.community.service;

import com.yxx.community.dto.PaginationDTO;
import com.yxx.community.dto.QuestionDTO;
import com.yxx.community.exception.CustomizeErrorCode;
import com.yxx.community.exception.CustomizeException;
import com.yxx.community.mapper.QuestionExtMapper;
import com.yxx.community.mapper.QuestionMapper;
import com.yxx.community.mapper.UserMapper;
import com.yxx.community.model.Question;
import com.yxx.community.model.QuestionExample;
import com.yxx.community.model.User;
import org.apache.ibatis.session.RowBounds;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 20:19 2020/1/27
 **/
@Service
public class QuestionService {

  @Autowired
  private UserMapper userMapper;
  @Autowired
  private QuestionMapper questionMapper;
  @Autowired
  private QuestionExtMapper questionExtMapper;

  public PaginationDTO list(String search,Integer page, Integer size) {

    if(!StringUtils.isEmpty(search)){
      search=StringUtils.replace(search, " ", "|");
    }
    PaginationDTO paginationDTO=new PaginationDTO();
    Integer totalCount = questionExtMapper.questionCount(search);
    page = checkPageAndSize(page, size, totalCount);
    paginationDTO.setPagination(totalCount,page,size);

    Integer offset=size*(page-1);
    List<Question> questions = questionExtMapper.list(offset,size,search);
    List<QuestionDTO> questionDTOList=new ArrayList<>();
    for (Question question : questions) {
      User user= userMapper.selectByPrimaryKey(question.getCreator());
      QuestionDTO questionDTO = new QuestionDTO();
      BeanUtils.copyProperties(question,questionDTO);
      questionDTO.setUser(user);
      questionDTOList.add(questionDTO);
    }
    paginationDTO.setData(questionDTOList);
    return paginationDTO;
  }
  public PaginationDTO listByUserId(Long userId, Integer page, Integer size) {
    PaginationDTO paginationDTO=new PaginationDTO();
    QuestionExample questionExample = new QuestionExample();
    questionExample.createCriteria().andCreatorEqualTo(userId);
    Integer totalCount = questionMapper.countByExample(questionExample);
    page = checkPageAndSize(page, size, totalCount);
    paginationDTO.setPagination(totalCount,page,size);
    Integer offset=size*(page-1);
    List<Question> questions = questionExtMapper.listByUserId(userId,offset,size);
    List<QuestionDTO> questionDTOList=new ArrayList<>();
    for (Question question : questions) {
      User user= userMapper.selectByPrimaryKey(question.getCreator());
      QuestionDTO questionDTO = new QuestionDTO();
      BeanUtils.copyProperties(question,questionDTO);
      questionDTO.setUser(user);
      questionDTOList.add(questionDTO);
    }
    paginationDTO.setData(questionDTOList);
    return paginationDTO;
  }

  public QuestionDTO getById(Long id) {
    Question question=questionMapper.selectByPrimaryKey(id);
    if(question==null){
      throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FIND);
    }
    QuestionDTO questionDTO = new QuestionDTO();
    BeanUtils.copyProperties(question,questionDTO);
    User user= userMapper.selectByPrimaryKey(question.getCreator());
    questionDTO.setUser(user);
    return questionDTO;
  }

  public void createOrUpdate(Question question) {
    if(question.getId()==null){
      //创建
      question.setGmtCreate(System.currentTimeMillis());
      question.setGmtModified(question.getGmtCreate());
      question.setViewCount(0);
      question.setCommentCount(0);
      question.setLikeCount(0);
      questionMapper.insert(question);
    }else{
      //更新
      question.setGmtModified(System.currentTimeMillis());
      Question updateQuestion = new Question();
      updateQuestion.setGmtModified(System.currentTimeMillis());
      updateQuestion.setTitle(question.getTitle());
      updateQuestion.setDescription(question.getDescription());
      updateQuestion.setTag(question.getTag());
      QuestionExample example = new QuestionExample();
      example.createCriteria().andIdEqualTo(question.getId());
      int updateed = questionMapper.updateByExampleSelective(updateQuestion, example);
      if(updateed!=1){
        throw new CustomizeException(CustomizeErrorCode.QUESTION_NOT_FIND);
      }
    }
  }

  public void inView(Long id) {
    Question question = new Question();
    question.setId(id);
    question.setViewCount(1);
    questionExtMapper.inView(question);
  }

  public List<QuestionDTO> selectRelated(QuestionDTO paramDto) {
    if(StringUtils.isEmpty(paramDto)){
      return new ArrayList<>();
    }
    String regexTag = StringUtils.replace(paramDto.getTag(), ",", "|");
    Question question = new Question();
    question.setId(paramDto.getId());
    question.setTag(regexTag);
    List<Question> questions = questionExtMapper.selectRelated(question);
    List<QuestionDTO> questionDTOS = questions.stream().map(q -> {
      QuestionDTO questionDTO = new QuestionDTO();
      BeanUtils.copyProperties(q,questionDTO);
      return questionDTO;
    }).collect(Collectors.toList());
    return questionDTOS;
  }

  @NotNull
  private Integer checkPageAndSize(Integer page, Integer size, Integer totalCount) {
    Integer totalPage=0;
    if(totalCount % size==0){
      totalPage=totalCount/size;
    }else {
      totalPage=totalCount/size+1;
    }
    if(page<1){
      page=1;
    }else if(page>totalPage){
      page=totalPage;
    }
    return page;
  }
}
